#!/usr/bin/env python
#coding=utf-8

import os
import sys
import gzip

def listGz(f):
	_list = []
	for _root, _dirs, _files in os.walk(f):
		for _f in _files:
			if _f.lower().endswith('.gz'):
				_list.append(os.path.join(_root, _f))
	
	return _list

def clearTempDir(d):
    try:
        if os.path.exists(d):
            for root, dirs, files in os.walk(d, topdown=False):
                for _name in files:
					try:
						os.remove(os.path.join(root, _name))
					except Exception, err:
						pass
                for _name in dirs:
					try:
						os.rmdir(os.path.join(root, _name))
					except Exception, err:
						pass
#            os.rmdir(d)
    except Exception, err:
        print 'Clear temp directory failed:', err
        

if __name__ == '__main__':
	if len(sys.argv) != 3:
		print '''usage process.prism.py [gz file folder] [output folder]'''
		sys.exit(0)
		
	_tarfolder = sys.argv[1]
	_outfolder = sys.argv[2]

	_dir = sys.path[0]
	
	_scriptPath = os.path.join(_dir, 'tmp\\execute.bat')
	_out = file(_scriptPath, 'w');
	
	_gdalData = os.path.join(_dir, 'gdal\\data')
	_gdalBin = os.path.join(_dir, 'gdal\\bin')
	_gdalCmd1 = os.path.join(_gdalBin, 'gdal_translate.exe')
	_gdalCmd2 = os.path.join(_gdalBin, 'gdalwarp.exe')
	
	if _gdalBin not in sys.path:
		_out.write('set PATH=' + _gdalBin + ';%PATH%\n')

	_out.write('set GDAL_DATA=' + _gdalData + '\n')
	
	_list = listGz(_tarfolder)
	
	if len(_list) == 0:
		print 'warning: not found any dataset'
		sys.exit(0)
	
	for i in range(len(_list)):
		print str(i + 1) + '/' + str(len(_list)), _list[i]
		
		_g = gzip.GzipFile(_list[i])
		
		_name = os.path.splitext(os.path.split(_list[i])[1])[0]
		
		_tmppath = os.path.join(os.path.join(_dir, 'tmp\\') + _name + '.txt')
		_tifpath = os.path.join(os.path.join(_dir, 'tmp\\') + _name + '.tif')
		_prjpath = os.path.join(_outfolder, _name + '.tif')
		
		print '  extracting...',
		_o = file(_tmppath, 'wb')
		_o.write(_g.read())
		_o.close()
		print 'ok'
		
		_out.write(_gdalCmd1 + ' -a_srs EPSG:4326 \"' + _tmppath + '\" \"' + _tifpath + '\"\n')
		_out.write(_gdalCmd2 + ' -r bilinear -dstnodata -9999 -t_srs \"+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=23 +lon_0=-96 +x_0=0 +y_0=0 +ellps=GRS80 +datum=NAD83 +units=m +no_defs\" \"' + _tifpath + '\" \"' + _prjpath + '\"\n')
#		_out.write(_gdalCmd2 + ' -r bilinear -dstnodata -9999 -t_srs EPSG:42303 \"' + _tifpath + '\" \"' + _prjpath + '\"\n')
		
	_out.close()

	if not os.path.exists(_outfolder):
		os.mkdir(_outfolder)
	
	print '-----------------------------------------'
	if raw_input(str(len(_list)) + ' datasets have been found, tranlate? (y/n):') == 'y':
	    os.system(_scriptPath)
	
	print '-----------------------------------------'
	print 'clean temp folder ...',
	clearTempDir(os.path.join(_dir, 'tmp\\'))
	print 'ok'
	
	